import React from 'react';
import { connect } from 'dva';
import { Button, DatePicker, Form, Icon, message, Modal, Radio, Spin, Upload, Table } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import styles from '../index.less';
import { ForecastTypeList, Lv1ClassifyTypeList } from '@/pages/Forecast/constants';

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 12 },
};

const DEFAULT_STATE = {
  forecastDate: moment().add(1, 'days'),
  lv1ClassifyType: undefined,
  file: undefined,
  errorInfoList: [],
};

const FormItem = Form.Item;

/**
 * Author: feixy
 * Date: 2019-07-11
 * Time: 11:36
 */
@Form.create()
@connect(({ loading }) => ({
  loading: loading.models.forecastScheduler,
}))
class ImportModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ...DEFAULT_STATE };
  }

  componentDidMount() {}

  onImportEvent = () => {
    const { file, forecastDate, lv1ClassifyType, forecastType } = this.state;
    if (!forecastType) {
      message.error('请选择预测类型');
      return;
    }
    if (!forecastDate) {
      message.error('请选择预测日期');
      return;
    }
    const checkTime = moment().endOf('day');
    if (checkTime.isAfter(forecastDate)) {
      message.error('只能上传T+1之后的运营计划表');
      return;
    }
    if (lv1ClassifyType === undefined) {
      message.error('请选择一级类目');
      return;
    }
    if (file === undefined) {
      message.error('请选择运营计划表文件');
      return;
    }
    const formData = new FormData();
    formData.append('file', file);
    formData.append('forecastDate', forecastDate.format('YYYY-MM-DD'));
    formData.append('lv1ClassifyType', lv1ClassifyType);
    formData.append('forecastType', forecastType);

    const { dispatch, handleModalVisible } = this.props;
    this.setState({ errorInfoList: [] });
    dispatch({
      type: 'forecastScheduler/importData',
      payload: formData,
      callback: ({ code, data }) => {
        if (code === 0) {
          message.success(data);
          handleModalVisible(true);
        } else {
          try {
            const errorInfoList = [];
            _.forOwn(JSON.parse(data), (value, key) => {
              if (value && value.length > 0) {
                value.forEach(item =>
                  errorInfoList.push({
                    id: errorInfoList.length,
                    warehouseName: key,
                    errorInfo: item,
                  })
                );
              }
            });
            this.setState({
              errorInfoList,
            });
          } catch (e) {
            message.error(data);
          }
        }
      },
    });
  };

  getUploadProps = () => {
    const { file } = this.state;
    const fileList = file ? [file] : undefined;
    return {
      accept: '.xlsx',
      fileList,
      beforeUpload: newFile => {
        this.setState({
          file: newFile,
        });
        return false;
      },
      onRemove: () => {
        this.setState({
          file: undefined,
        });
      },
    };
  };

  onStateChange = (key, mapper = e => e) => value => {
    this.setState({
      [key]: mapper(value),
    });
  };

  renderErrorInfo = () => {
    const { errorInfoList = [] } = this.state;
    if (!errorInfoList || errorInfoList.length <= 0) {
      return null;
    }
    const columns = [
      {
        title: '仓库名称',
        align: 'center',
        width: '30%',
        dataIndex: 'warehouseName',
      },
      { title: '错误信息', dataIndex: 'errorInfo' },
    ];

    return (
      <div className="errorInfo" style={{ maxHeight: '300px' }}>
        <Table
          columns={columns}
          dataSource={errorInfoList}
          scroll={{ y: '250px' }}
          pagination={false}
          rowKey={record => record.id}
          size="small"
        />
      </div>
    );
  };

  render() {
    const { handleModalVisible, loading } = this.props;
    const { forecastDate, lv1ClassifyType, forecastType } = this.state;
    return (
      <Modal
        destroyOnClose
        maskClosable={false}
        width={650}
        okText="导入"
        onOk={this.onImportEvent}
        onCancel={() => handleModalVisible()}
        style={{ top: 20 }}
        visible
        title="导入运营计划表"
        className={styles.importModal}
        confirmLoading={loading}
      >
        <Spin spinning={loading} tip="导入中...">
          <Form>
            <Form.Item {...formItemLayout} label="预测类型">
              <Radio.Group
                value={forecastType}
                onChange={this.onStateChange('forecastType', e => e.target.value)}
                style={{ width: '100%' }}
              >
                {ForecastTypeList.filter(item => item.code !== 0).map(item => (
                  <Radio value={item.code} key={item.code}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item {...formItemLayout} label="一级类目">
              <Radio.Group
                value={lv1ClassifyType}
                onChange={this.onStateChange('lv1ClassifyType', e => e.target.value)}
                style={{ width: '100%' }}
              >
                {Lv1ClassifyTypeList.filter(item => item.code !== 0).map(item => (
                  <Radio value={item.code} key={item.code}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <FormItem key="forecastDate" {...formItemLayout} label="预测日期">
              <DatePicker
                placeholder="请选择预测日期"
                value={forecastDate}
                onChange={this.onStateChange('forecastDate')}
                disabledDate={current => {
                  return current && current < moment().endOf('day');
                }}
              />
            </FormItem>
            <Form.Item {...formItemLayout} label="运营计划表">
              <Upload {...this.getUploadProps()}>
                <Button size="small">
                  <Icon type="upload" />
                  选择文件
                </Button>
              </Upload>
            </Form.Item>
          </Form>
          {this.renderErrorInfo()}
        </Spin>
      </Modal>
    );
  }
}

export default ImportModal;
